#!/bin/sh

VER=0.1
echo "Custom ROOTFS Installer $VER"
echo "---------------------------"
echo "   Licensed under GPL v3"
echo ""
echo "Thanks for tim66,eXpressionist,movcale and many"
echo "other people from http://rutracker.org/forum/viewtopic.php?t=2588024"
echo ""
echo "WARNING! This script will perform potentially dangerous operations"
echo "such as updating the root file system and configuration changes".
echo "If you are not sure - press Control-C right now!!!"
echo "This is the last chance to cancel the installation"
echo ""
echo "Press Enter to continue"
read T
echo "$T" > /dev/null
clear
ROOT_MD5="41bf8a1491617fbf411c7a1d9a127296"
echo -n "Check MD5 hash for root.sqfs ... "
MD5=`md5sum root.sqfs | awk '{print $1}' | grep -c $ROOT_MD5`
if [ $MD5 -le 0 ]; then
  echo "FAIL"
  echo "ROOTFS image was damaged"
  exit 1
fi
echo "OK"
echo "1. Backup old ROOTFS to mtdblock3.bin"
dd if=/dev/mtdblock3 of=./mtdblock3.bin
echo "2. Flash ROOTFS into ROM"
dd if=./root.sqfs of=/dev/mtdblock3
echo "3. Test new ROM with flashed image"
dd if=/dev/mtdblock3 of=./rootfs.new
echo -n "Checking ... "
MD5=`md5sum rootfs.new | awk '{print $1}' | grep -c $ROOT_MD5`
if [ $MD5 -le 0 ]; then
  echo "FAIL"
  echo "ROOTFS image was flashed unsuccessful"
  echo "Write back"
  dd of=/dev/mtdblock3 if=./mtdblock3.bin
  exit 1
fi
echo "OK"
rm -f ./rootfs.new
echo "4. Write configuration into /conf partition"
echo -n "4.1 Backup ... "
[ -d /conf/.config ] && tar czvf /conf/config_`date +%F`.tar.gz /conf/.config
[ -d /conf/.cron ] && tar czvf /conf/cron_`date +%F`.tar.gz /conf/.cron
[ -d /conf/transmission ] && tar czvf /conf/transmission_`date +%F`.tar.gz /conf/transmission
echo "Done"
echo -n "4.2 Copy files ... "
chmod -R 755 conf/.cron
cp -af conf/.cron /conf/
cp -af conf/.config /conf/
cp -af conf/transmission /conf/
mv /etc/init.d/rc.reboot /etc/init.d/rc.reboot.orig
cp -f conf/.cron/rc.reboot /etc/init.d/
echo "Done"
echo "Well done! The seedbox get ready!"
echo "After reboot Transmission will be responsible for http://<seedbox address>:9091"
echo "Login - user, Password - password"
echo "In web-interface, section TOOLS will contain item WGET downloader"
echo "Check config:"
echo "  in /conf/.config/settings.json - for transmission"
echo "  in /conf/.cron/web2wget.conf - for wget"
echo ""
echo "Press ENTER for reboot or Control-C for cancel reboot and follow shell"
read T
echo "$T" > /dev/null
cd /
/etc/init.d/rc.reboot
